package com.zyf.wjy.init;

import com.zyf.wjy.entity.*;
import com.zyf.wjy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据初始化器
 */
@Component
public class DataInitializer implements ApplicationRunner {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FieldService fieldService;
    
    @Autowired
    private CropService cropService;
    
    @Autowired
    private MaterialService materialService;
    
    @Autowired
    private PlantingPlanService plantingPlanService;
    
    @Autowired
    private FarmingRecordService farmingRecordService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private SalesRecordService salesRecordService;
    
    @Autowired
    private NewsService newsService;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 检查是否已有数据
        if (!userService.findAll().isEmpty()) {
            System.out.println("数据已存在，跳过初始化");
            return;
        }
        
        System.out.println("开始初始化数据...");
        
        // 初始化用户
        initUsers();
        
        // 初始化地块
        initFields();
        
        // 初始化作物
        initCrops();
        
        // 初始化农资
        initMaterials();
        
        // 初始化种植计划
        initPlantingPlans();
        
        // 初始化农事记录
        initFarmingRecords();
        
        // 初始化产品
        initProducts();
        
        // 初始化销售记录
        initSalesRecords();
        
        // 初始化新闻
        initNews();
        
        System.out.println("数据初始化完成！");
    }
    
    private void initUsers() {
        List<User> users = new ArrayList<>();
        
        User admin = new User();
        admin.setUsername("admin");
        admin.setPassword("admin123");
        admin.setRealName("系统管理员");
        admin.setRole("admin");
        admin.setPhone("13800138000");
        admin.setEmail("admin@farm.com");
        admin.setStatus(1);
        admin.setCreateTime(LocalDateTime.now());
        users.add(admin);
        
        User manager = new User();
        manager.setUsername("manager");
        manager.setPassword("manager123");
        manager.setRealName("张三");
        manager.setRole("manager");
        manager.setPhone("13800138001");
        manager.setEmail("manager@farm.com");
        manager.setStatus(1);
        manager.setCreateTime(LocalDateTime.now());
        users.add(manager);
        
        User visitor = new User();
        visitor.setUsername("visitor");
        visitor.setPassword("visitor123");
        visitor.setRealName("李四");
        visitor.setRole("visitor");
        visitor.setPhone("13800138002");
        visitor.setEmail("visitor@farm.com");
        visitor.setStatus(1);
        visitor.setCreateTime(LocalDateTime.now());
        users.add(visitor);
        
        userService.saveAll(users);
        System.out.println("用户数据初始化完成");
    }
    
    private void initFields() {
        List<Field> fields = new ArrayList<>();
        
        Field field1 = new Field();
        field1.setFieldCode("F001");
        field1.setFieldName("东区1号田");
        field1.setArea(10.5);
        field1.setLocation("东区");
        field1.setSoilType("黏土");
        field1.setRemark("配备滴灌系统");
        field1.setStatus(1);
        field1.setCreateTime(LocalDateTime.now());
        fields.add(field1);
        
        Field field2 = new Field();
        field2.setFieldCode("F002");
        field2.setFieldName("西区2号田");
        field2.setArea(8.3);
        field2.setLocation("西区");
        field2.setSoilType("壤土");
        field2.setRemark("配备喷灌系统");
        field2.setStatus(1);
        field2.setCreateTime(LocalDateTime.now());
        fields.add(field2);
        
        Field field3 = new Field();
        field3.setFieldCode("F003");
        field3.setFieldName("南区3号田");
        field3.setArea(12.0);
        field3.setLocation("南区");
        field3.setSoilType("砂壤土");
        field3.setRemark("配备渠灌系统");
        field3.setStatus(0);
        field3.setCreateTime(LocalDateTime.now());
        fields.add(field3);
        
        fieldService.saveAll(fields);
        System.out.println("地块数据初始化完成");
    }
    
    private void initCrops() {
        List<Crop> crops = new ArrayList<>();
        
        Crop crop1 = new Crop();
        crop1.setCropName("水稻");
        crop1.setVariety("优质稻");
        crop1.setGrowthCycle(120);
        crop1.setSowingSeason("春季");
        crop1.setHarvestSeason("夏季");
        crop1.setSuitableSoil("黏土、壤土");
        crop1.setSuitableTemperature("20-30℃");
        crop1.setDescription("优质粮食作物，产量高，品质好");
        crop1.setCreateTime(LocalDateTime.now());
        crops.add(crop1);
        
        Crop crop2 = new Crop();
        crop2.setCropName("小麦");
        crop2.setVariety("高产小麦");
        crop2.setGrowthCycle(180);
        crop2.setSowingSeason("秋季");
        crop2.setHarvestSeason("夏季");
        crop2.setSuitableSoil("壤土、砂壤土");
        crop2.setSuitableTemperature("15-25℃");
        crop2.setDescription("主要粮食作物，耐寒性强");
        crop2.setCreateTime(LocalDateTime.now());
        crops.add(crop2);
        
        Crop crop3 = new Crop();
        crop3.setCropName("番茄");
        crop3.setVariety("樱桃番茄");
        crop3.setGrowthCycle(90);
        crop3.setSowingSeason("春季");
        crop3.setHarvestSeason("夏季");
        crop3.setSuitableSoil("壤土");
        crop3.setSuitableTemperature("22-28℃");
        crop3.setDescription("优质蔬菜，营养丰富，口感好");
        crop3.setCreateTime(LocalDateTime.now());
        crops.add(crop3);
        
        cropService.saveAll(crops);
        System.out.println("作物数据初始化完成");
    }
    
    private void initMaterials() {
        List<Material> materials = new ArrayList<>();
        
        Material material1 = new Material();
        material1.setMaterialName("有机肥料");
        material1.setMaterialType("fertilizer");
        material1.setSpecification("50kg/袋");
        material1.setUnit("吨");
        material1.setQuantity(50.0);
        material1.setPrice(1200.0);
        material1.setSupplier("绿色农资公司");
        material1.setRemark("有机认证肥料");
        material1.setCreateTime(LocalDateTime.now());
        materials.add(material1);
        
        Material material2 = new Material();
        material2.setMaterialName("优质稻种");
        material2.setMaterialType("seed");
        material2.setSpecification("1kg/袋");
        material2.setUnit("kg");
        material2.setQuantity(500.0);
        material2.setPrice(15.0);
        material2.setSupplier("种子研究所");
        material2.setRemark("高产优质品种");
        material2.setCreateTime(LocalDateTime.now());
        materials.add(material2);
        
        Material material3 = new Material();
        material3.setMaterialName("生物农药");
        material3.setMaterialType("pesticide");
        material3.setSpecification("500ml/瓶");
        material3.setUnit("瓶");
        material3.setQuantity(100.0);
        material3.setPrice(50.0);
        material3.setSupplier("生物科技公司");
        material3.setRemark("生物农药，无残留");
        material3.setCreateTime(LocalDateTime.now());
        materials.add(material3);
        
        materialService.saveAll(materials);
        System.out.println("农资数据初始化完成");
    }
    
    private void initPlantingPlans() {
        List<PlantingPlan> plans = new ArrayList<>();
        
        PlantingPlan plan1 = new PlantingPlan();
        plan1.setPlanCode("P001");
        plan1.setFieldId(1L);
        plan1.setFieldName("东区1号田");
        plan1.setCropId(1L);
        plan1.setCropName("水稻");
        plan1.setPlantingArea(10.5);
        plan1.setPlannedSowingDate(LocalDate.of(2024, 3, 1));
        plan1.setExpectedHarvestDate(LocalDate.of(2024, 7, 1));
        plan1.setExpectedYield(5000.0);
        plan1.setManager("张三");
        plan1.setStatus("executing");
        plan1.setCreateTime(LocalDateTime.now());
        plans.add(plan1);
        
        PlantingPlan plan2 = new PlantingPlan();
        plan2.setPlanCode("P002");
        plan2.setFieldId(2L);
        plan2.setFieldName("西区2号田");
        plan2.setCropId(3L);
        plan2.setCropName("番茄");
        plan2.setPlantingArea(8.3);
        plan2.setPlannedSowingDate(LocalDate.of(2024, 2, 15));
        plan2.setExpectedHarvestDate(LocalDate.of(2024, 5, 15));
        plan2.setExpectedYield(3000.0);
        plan2.setManager("李四");
        plan2.setStatus("executing");
        plan2.setCreateTime(LocalDateTime.now());
        plans.add(plan2);
        
        plans.forEach(plan -> plantingPlanService.save(plan));
        System.out.println("种植计划数据初始化完成");
    }
    
    private void initFarmingRecords() {
        List<FarmingRecord> records = new ArrayList<>();
        
        FarmingRecord record1 = new FarmingRecord();
        record1.setRecordCode("FR001");
        record1.setFieldId(1L);
        record1.setFieldName("东区1号田");
        record1.setCropId(1L);
        record1.setCropName("水稻");
        record1.setFarmingType("sowing");
        record1.setFarmingDate(LocalDate.of(2024, 3, 1));
        record1.setMaterialId(2L);
        record1.setMaterialName("优质稻种");
        record1.setQuantity(50.0);
        record1.setUnit("kg");
        record1.setCost(750.0);
        record1.setManager("张三");
        record1.setDescription("春季水稻播种");
        record1.setCreateTime(LocalDateTime.now());
        records.add(record1);
        
        FarmingRecord record2 = new FarmingRecord();
        record2.setRecordCode("FR002");
        record2.setFieldId(1L);
        record2.setFieldName("东区1号田");
        record2.setCropId(1L);
        record2.setCropName("水稻");
        record2.setFarmingType("fertilizing");
        record2.setFarmingDate(LocalDate.of(2024, 3, 15));
        record2.setMaterialId(1L);
        record2.setMaterialName("有机肥料");
        record2.setQuantity(2.0);
        record2.setUnit("吨");
        record2.setCost(2400.0);
        record2.setManager("张三");
        record2.setDescription("基肥施用");
        record2.setCreateTime(LocalDateTime.now());
        records.add(record2);
        
        FarmingRecord record3 = new FarmingRecord();
        record3.setRecordCode("FR003");
        record3.setFieldId(2L);
        record3.setFieldName("西区2号田");
        record3.setCropId(3L);
        record3.setCropName("番茄");
        record3.setFarmingType("irrigation");
        record3.setFarmingDate(LocalDate.of(2024, 3, 20));
        record3.setCost(500.0);
        record3.setManager("李四");
        record3.setDescription("首次灌溉");
        record3.setCreateTime(LocalDateTime.now());
        records.add(record3);
        
        records.forEach(record -> farmingRecordService.save(record));
        System.out.println("农事记录数据初始化完成");
    }
    
    private void initProducts() {
        List<Product> products = new ArrayList<>();
        
        Product product1 = new Product();
        product1.setProductCode("P001");
        product1.setProductName("优质大米");
        product1.setGrade("A");
        product1.setUnit("kg");
        product1.setQuantity(5000.0);
        product1.setOrigin("东区1号田");
        product1.setHarvestDate(LocalDate.of(2024, 6, 30));
        product1.setStockInDate(LocalDate.of(2024, 7, 1));
        product1.setShelfLife(365);
        product1.setCostPrice(5.0);
        product1.setSuggestedPrice(8.0);
        product1.setDescription("优质有机大米，口感香糯，营养丰富");
        product1.setCreateTime(LocalDateTime.now());
        products.add(product1);
        
        Product product2 = new Product();
        product2.setProductCode("P002");
        product2.setProductName("有机番茄");
        product2.setGrade("A");
        product2.setUnit("kg");
        product2.setQuantity(2000.0);
        product2.setOrigin("西区2号田");
        product2.setHarvestDate(LocalDate.of(2024, 5, 10));
        product2.setStockInDate(LocalDate.of(2024, 5, 10));
        product2.setShelfLife(15);
        product2.setCostPrice(3.0);
        product2.setSuggestedPrice(6.0);
        product2.setDescription("新鲜采摘，绿色有机，味道鲜美");
        product2.setCreateTime(LocalDateTime.now());
        products.add(product2);
        
        Product product3 = new Product();
        product3.setProductCode("P003");
        product3.setProductName("有机小麦");
        product3.setGrade("B");
        product3.setUnit("kg");
        product3.setQuantity(3000.0);
        product3.setOrigin("南区3号田");
        product3.setHarvestDate(LocalDate.of(2024, 6, 15));
        product3.setStockInDate(LocalDate.of(2024, 6, 15));
        product3.setShelfLife(180);
        product3.setCostPrice(3.5);
        product3.setSuggestedPrice(5.5);
        product3.setDescription("天然种植，无化学添加");
        product3.setCreateTime(LocalDateTime.now());
        products.add(product3);
        
        productService.saveAll(products);
        System.out.println("产品数据初始化完成");
    }
    
    private void initSalesRecords() {
        List<SalesRecord> records = new ArrayList<>();
        
        SalesRecord record1 = new SalesRecord();
        record1.setSalesCode("S001");
        record1.setProductId(1L);
        record1.setProductName("优质大米");
        record1.setQuantity(500.0);
        record1.setUnit("kg");
        record1.setPrice(8.0);
        record1.setTotalAmount(4000.0);
        record1.setCustomerName("绿色超市");
        record1.setCustomerPhone("13900001111");
        record1.setSalesman("张三");
        record1.setSalesDate(LocalDate.of(2024, 7, 5));
        record1.setPaymentMethod("transfer");
        record1.setCreateTime(LocalDateTime.now());
        records.add(record1);
        
        SalesRecord record2 = new SalesRecord();
        record2.setSalesCode("S002");
        record2.setProductId(2L);
        record2.setProductName("有机番茄");
        record2.setQuantity(300.0);
        record2.setUnit("kg");
        record2.setPrice(6.0);
        record2.setTotalAmount(1800.0);
        record2.setCustomerName("有机农场直销店");
        record2.setCustomerPhone("13900002222");
        record2.setSalesman("李四");
        record2.setSalesDate(LocalDate.of(2024, 5, 12));
        record2.setPaymentMethod("cash");
        record2.setCreateTime(LocalDateTime.now());
        records.add(record2);
        
        SalesRecord record3 = new SalesRecord();
        record3.setSalesCode("S003");
        record3.setProductId(1L);
        record3.setProductName("优质大米");
        record3.setQuantity(1000.0);
        record3.setUnit("kg");
        record3.setPrice(8.0);
        record3.setTotalAmount(8000.0);
        record3.setCustomerName("批发市场");
        record3.setCustomerPhone("13900003333");
        record3.setSalesman("张三");
        record3.setSalesDate(LocalDate.of(2024, 7, 10));
        record3.setPaymentMethod("transfer");
        record3.setCreateTime(LocalDateTime.now());
        records.add(record3);
        
        records.forEach(record -> salesRecordService.save(record));
        System.out.println("销售记录数据初始化完成");
    }
    
    private void initNews() {
        List<News> newsList = new ArrayList<>();
        
        News news1 = new News();
        news1.setTitle("智慧农场正式投入运营");
        news1.setType("announcement");
        news1.setSummary("经过半年的筹备，智慧农场管理系统正式上线运营，标志着我们农场进入数字化管理新时代。");
        news1.setContent("经过半年的精心筹备和系统测试，智慧农场管理系统于今日正式投入运营。该系统采用先进的物联网技术和大数据分析，实现了农场生产全流程的数字化管理，将大幅提升我们的生产效率和产品质量。");
        news1.setStatus(1);
        news1.setIsTop(1);
        news1.setAuthor("系统管理员");
        news1.setPublishTime(LocalDateTime.now().minusDays(5));
        news1.setViewCount(156);
        news1.setCreateTime(LocalDateTime.now().minusDays(5));
        newsList.add(news1);
        
        News news2 = new News();
        news2.setTitle("2024年春季种植计划启动");
        news2.setType("news");
        news2.setSummary("今年春季，我们计划种植优质水稻10.5亩，有机番茄8.3亩，预计总产值将突破50万元。");
        news2.setContent("根据市场需求和土壤条件分析，2024年春季种植计划已经正式启动。计划在东区1号田种植优质水稻10.5亩，西区2号田种植有机番茄8.3亩。所有种植将采用有机肥料和生物农药，确保产品绿色健康。");
        news2.setStatus(1);
        news2.setIsTop(1);
        news2.setAuthor("张三");
        news2.setPublishTime(LocalDateTime.now().minusDays(3));
        news2.setViewCount(89);
        news2.setCreateTime(LocalDateTime.now().minusDays(3));
        newsList.add(news2);
        
        News news3 = new News();
        news3.setTitle("有机认证通过审核");
        news3.setType("announcement");
        news3.setSummary("喜讯！我们的农产品已通过国家有机产品认证，可以正式使用有机产品标识。");
        news3.setContent("经过严格的现场检查和产品检测，我们的优质大米、有机番茄等产品已成功通过国家有机产品认证。这标志着我们的产品质量得到了权威认可，为产品进入高端市场打开了大门。");
        news3.setStatus(1);
        news3.setIsTop(0);
        news3.setAuthor("李四");
        news3.setPublishTime(LocalDateTime.now().minusDays(1));
        news3.setViewCount(234);
        news3.setCreateTime(LocalDateTime.now().minusDays(1));
        newsList.add(news3);
        
        News news4 = new News();
        news4.setTitle("农场开放日活动通知");
        news4.setType("notice");
        news4.setSummary("本月28日，我们将举办农场开放日活动，欢迎市民朋友前来参观体验。");
        news4.setContent("为了让更多市民了解现代农业和有机种植，我们将在本月28日（周六）举办农场开放日活动。活动内容包括：参观智慧农场、体验农事活动、品尝有机农产品等。欢迎广大市民朋友携家人前来参观体验！");
        news4.setStatus(1);
        news4.setIsTop(1);
        news4.setAuthor("张三");
        news4.setPublishTime(LocalDateTime.now());
        news4.setViewCount(45);
        news4.setCreateTime(LocalDateTime.now());
        newsList.add(news4);
        
        newsService.saveAll(newsList);
        System.out.println("新闻数据初始化完成");
    }
}
